<?php
//define cache path
	class cache {
	public $check_cache = false;
	public function save( $name, $value, $timeout = 0,$sub="",$mem="") {
		$name=md5($name);
		if($mem==1 && class_exists('Memcache')){
			//Store in memcache-------------
			$memcache = new Memcache;
			$memcache->connect('localhost', 11211);
			$memcache->set($name, $value, false, $timeout);
			//End store in memcache---------
		}else{
				//start cache file
				$cache_file = "<?PHP\n\n";
				//set description to cache file
				$cache_file .= "/*\n	CACHE FILE NAME: ". $name ."\n	GENERATE TIME: ". date('c') ."\n*/\n\n";
				//set data to cache file
				$timeout = $timeout + time();
				$cache_file .= "//cache timeout\n" . '$timeout = '. $timeout . ";\n\n";
				//set variable to cache
				$cache_file .= "//cache content\n" . '$cache_variable = '. var_export($value, true) .';';
			//end cache
				$cache_file .= "\n\n?>";
				//return cache to save
				if($sub!=""){
					$path=CACHE_PATH.'/'.trim($sub);
				}else{
						$path=CACHE_PATH;
				}
				if(!is_dir($path)){
						mkdir($path,0775,true);
				}
				return file_put_contents( $path .'/'. $name .'.php', $cache_file);
		}
	}
	
	/**
	 * load cache 
	 *
	 * @return: mixed
	 */
	
	public function load( $name,$sub="",$mem="") {
		$name=md5($name);
		if($mem==1 && class_exists('Memcache')){
			//echo "Memcache";
			//GET MEMCACHE------
			$memcache = new Memcache;
			$memcache->connect('localhost', 11211);
			$data= $memcache->get($name);
			if($data){
			return $data;
			}else{
			return false;
			}
			//End get memcache----
		}else{
						//chech was cache exists
						if($sub!=""){
								$path=CACHE_PATH.'/'.trim($sub);
							}else{
								$path=CACHE_PATH;
							}
					if( file_exists($path.'/'. $name .'.php')) {
								//load cache
							include $path.'/'. $name .'.php';
					//chech was cache no expired
							if($timeout > time()) {
							}
							else
							{
							return false;
							}
					// return cache
							return $cache_variable;
			
					} else {
						// return error
							return false;
							}
		}
	}
	public function flush( $name,$sub="",$mem="") {
		$name=md5($name);
		if(class_exists('Memcache') && $mem==1){
			$memcache = new Memcache;
			$memcache->connect('localhost', 11211);
			$memcache->delete($name);
		}else{
				if($sub!=""){
						$path=CACHE_PATH.'/'.trim($sub);
					}else{
						$path=CACHE_PATH;
					}
				if( file_exists($path.'/'. $name .'.php')) {
					unlink($path.'/'. $name .'.php');
				}
			} 
	}
}